package com.ruoyi.wvp.controller;

import java.util.List;
import java.util.Date;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wvp.domain.Surveillance;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.wvp.domain.AddressUnit;
import com.ruoyi.wvp.service.IAddressUnitService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.enums.DeletedEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

/**
 * 行政单位Controller
 *
 * @author ruoyi
 * @date 2024-07-22
 */
@RestController
@RequestMapping("/wvp/addressUnit")
@Tag(name = "【行政单位】管理")
public class AddressUnitController extends BaseController {
    @Autowired
    private IAddressUnitService addressUnitService;

    /**
     * 查询行政单位列表
     */
    @Operation(summary = "查询行政单位列表")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:list')")
    @GetMapping("/list")
    public TableDataInfo list(AddressUnit addressUnit) {
//        Page<AddressUnit> page = getPage();
        List<AddressUnit> addressUnits = addressUnitService.listAll(addressUnit);
        return getTableDataInfo(addressUnits);
    }




    /**
     * 查询行政单位列表（排除节点）
     */
    @Operation(summary = "查询行政单位列表", description = "排除节点")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:list')")
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id) {
        List<AddressUnit> depts = addressUnitService.listAll(new AddressUnit());
        depts.removeIf(d -> d.getId().intValue() == id || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""));
        return success(depts);
    }


    /**
     * 导出行政单位列表
     */
    @Operation(summary = "导出行政单位列表")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:export')")
    @Log(title = "行政单位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response, AddressUnit addressUnit) {
        List<AddressUnit> list = addressUnitService.listAll(addressUnit);
        ExcelUtil<AddressUnit> util = new ExcelUtil<AddressUnit>(AddressUnit.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取行政单位详细信息
     */
    @Operation(summary = "获取行政单位详细信息")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(addressUnitService.getById(id));
    }

    /**
     * 新增行政单位
     */
    @Operation(summary = "新增行政单位")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:add')")
    @Log(title = "行政单位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AddressUnit addressUnit) {
        addressUnit.setDeleted(DeletedEnum.NOMAL.getValue());
        addressUnit.setCreateBy(getUsername());
        addressUnit.setCreateTime(new Date());
        AddressUnit info = addressUnitService.getById(addressUnit.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("行政单位停用，不允许新增");
        }
        addressUnit.setAncestors(info.getAncestors() + Constants.DEPT_SPLIT_STR + addressUnit.getParentId());
        return toAjax(addressUnitService.save(addressUnit));
    }

    /**
     * 修改行政单位
     */
    @Operation(summary = "修改行政单位")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:edit')")
    @Log(title = "行政单位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AddressUnit addressUnit) {
        return  toAjax(addressUnitService.edit(addressUnit));
    }

    /**
     * 删除行政单位
     */
    @Operation(summary = "删除行政单位")
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:remove')")
    @Log(title = "行政单位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable(name = "ids") Long[] ids) {
        QueryWrapper<AddressUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", List.of(ids));
        AddressUnit addressUnit = new AddressUnit();
        addressUnit.setUpdateTime(new Date());
        addressUnit.setUpdateBy(getLoginUser().getUser().getUserName());
        addressUnit.setDeleted(DeletedEnum.DELETED.getValue());
        return toAjax(addressUnitService.update(addressUnit, queryWrapper));
    }

    @GetMapping("/listChild/{id}")
    @ResponseBody
    public AjaxResult listChild(@PathVariable Long id){
        AddressUnit addressUnit = new AddressUnit();
        addressUnit.setParentId(id);
        List<AddressUnit> depts = addressUnitService.listAll(addressUnit);
        return success(depts);
    }



    @Operation(summary = "导入行政单位")
    @Log(title = "行政单位管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('wvp:addressUnit:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<AddressUnit> util = new ExcelUtil<AddressUnit>(AddressUnit.class);
        List<AddressUnit> list = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = addressUnitService.importData(list, updateSupport, operName);
        return success(message);
    }

    @Operation(summary = "获取导入行政单位模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<AddressUnit> util = new ExcelUtil<AddressUnit>(AddressUnit.class);
        util.importTemplateExcel(response, "行政单位数据");
    }

    @PostMapping("/streetList")
    public AjaxResult streetList(){

        return AjaxResult.success(addressUnitService.streetList());
    }


//    @Anonymous
//    @GetMapping("/test")
//    public String test(){
//        addressUnitService.updateLevel();
//        return "success";
//    }

}
